package sync.ssc;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sync.bean.SSCBean;
import sync.bean.SSCFiveBean;
import sync.bean.SSCFiveUpdateBean;
import sync.bean.SSCLastResultBean;
import sync.bean.SSCPlanBean;
import sync.db.ConnectionPool;
import sync.db.DBHelper;
import sync.utils.Utils;

public class SyncSSCPlanFive {

	private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

	public void syncData(){
		String[] wyurls = new String[]{
				"http://cai.163.com/shahao/cqssc/wanwei_20.html",
				"http://zx.caipiao.163.com/shahao/cqssc/qianwei_20.html",
				"http://zx.caipiao.163.com/shahao/cqssc/baiwei_20.html",
				"http://zx.caipiao.163.com/shahao/cqssc/shiwei_20.html",
				"http://zx.caipiao.163.com/shahao/cqssc/gewei_20.html"
		};
		String[] urls = new String[]{
				"http://cp.360.cn/shdd/shax?LotID=255401&ItemID=1001&TopCount=20&r=0.23030921292132955",
				"http://cp.360.cn/shdd/shax?LotID=255401&ItemID=1002&TopCount=20&r=0.328937007629138",
				"http://cp.360.cn/shdd/shax?LotID=255401&ItemID=1003&TopCount=20&r=0.5303719027945568",
				"http://cp.360.cn/shdd/shax?LotID=255401&ItemID=1004&TopCount=20&r=0.27278835260896694",
				"http://cp.360.cn/shdd/shax?LotID=255401&ItemID=1005&TopCount=20&r=0.4838120017314027"
		};
		for(int i = 0; i < urls.length; i++){
			try {
				getWangyiData(wyurls[i],urls[i],i+1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	// 第三种抓取方式，直接去网易杀号网站获取
	public void getWangyiData(String purl,String purl3,int position)throws Exception{
		URL url = new URL(purl);
		Document doc = Jsoup.parse(url, 5000);
		Elements tbodys = doc.getElementsByTag("tbody");
		Elements trs = tbodys.get(0).getElementsByTag("tr");
		Elements trs2 = tbodys.get(1).getElementsByTag("tr");
		// 传递3个不同的需要的tr过去  
		// 第一个是当前杀号的
		Element tr = trs.get(trs.size()-2);
		// 第二个是上期的
		Element tr1 = trs.get(trs.size()-4);
		// 第三个是正确率的
		Element tr2 = trs2.get(3);
		String qihao = "20"+tr.getElementsByTag("td").get(0).html();
		String wangyidata = dealData( tr,tr1,tr2);
		String data360 = get360Data(purl3);
		String lastQihao = "20"+tr1.getElementsByTag("td").get(0).html();
		saveToDatabase(qihao,lastQihao,wangyidata,data360,position);
	}

	// 处理网易出来的数据  tr代表当前数据    tr2代表正确率数据 t1代表上一期的数据
	private String dealData(Element tr,Element tr1,Element tr2){
		String wangyidata = "";
		// 循环正确率的td，先找出全对的
		Elements tds2 = tr2.getElementsByTag("td");
		Elements tds = tr.getElementsByTag("td");
		//System.out.println(tds);
		String level0nums = "";
		String level2nums = "";
		for(int i = 0; i < tds2.size(); i++){
			String text = tds2.get(i).html();
			if("全对".equals(text)){
				// 获取全对情况下对应的数据
				Elements spans = tds.get(i+1).getElementsByTag("span");
				String number = spans.get(0).html();
				if(!level0nums.contains(number)){
					level0nums = level0nums+number;
				}
			}
			if(text.contains("95%")){
				// 获取全对情况下对应的数据
				Elements spans = tds.get(i+1).getElementsByTag("span");
				String number = spans.get(0).html();
				if(!level2nums.contains(number)){
					level2nums = level2nums+number;
				}
			}
		}
		String level1nums = "";
		// 循环上一期，先找出上一期错了的
		Elements tds1 = tr1.getElementsByTag("td");
		for(int j = 0; j < tds1.size(); j++){
			String txt = tds1.get(j).html();
			if(txt.contains("iconWrong")){
				// 并且正确率在88%以上才取用
				Integer zql = Integer.parseInt(tds2.get(j-1).html().replace("%", ""));
				if(zql > 88){
					Elements pans = tds.get(j).getElementsByTag("span");
					String a = pans.get(0).html();;
					if(!level1nums.contains(a)){
						level1nums = level1nums+a;
					}
				}
			}
		}
		// 获取当前期的所有数据，并得出没有被杀的号
		String b = "";
		for(int k = 2; k < tds.size()-1; k++){
			Element txt1 = tds.get(k);
			Elements ans = txt1.getElementsByClass("select");
			b = b+ans.get(0).html();
		}
		String nums = Utils.filterData(b);
		wangyidata = level0nums+","+level1nums+","+level2nums+","+nums;
		return wangyidata;
	}

	private String get360Data(String purl){
		String data = "";
		try {
			URL url = new URL(purl);
			Document doc = Jsoup.parse(url, 5000);
			Elements tbodys = doc.getElementsByTag("tbody");
			Elements trs = tbodys.get(0).getElementsByTag("tr");
			// 正确率的tr
			Element tr3 = trs.get(trs.size()-3);
			// 上一期的
			Element tr2 = trs.get(trs.size()-8);
			// 当前杀号
			Element tr = trs.get(trs.size()-7);
			data = deal360Data(tr,tr2,tr3);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	// 处理360出来的数据  tr代表当前数据  tr2代表正确率数据  t1代表上一期的数据
	private String deal360Data(Element tr,Element tr1,Element tr2){
		String wangyidata = "";
		// 循环正确率的td，先找出全对的
		Elements tds2 = tr2.getElementsByClass("red");
		Elements tds = tr.getElementsByClass("tbg1");
		Elements tds1 = tr1.getElementsByClass("tbg4");
		String level0nums = "";
		String level2nums = "";
		for(int i = 0; i < tds2.size()-1; i++){
			String text = tds2.get(i).toString();
			if(text.contains("100%")){
				// 获取全对情况下对应的数据
				Elements bs = tds.get(i+1).getElementsByTag("b");
				String number = bs.get(0).html();
				if(!level0nums.contains(number)){
					level0nums = level0nums+number;
				}
			}
			if(text.contains("95%")){
				// 获取全对情况下对应的数据
				Elements bs = tds.get(i+1).getElementsByTag("b");
				String number = bs.get(0).html();
				if(!level2nums.contains(number)){
					level2nums = level2nums+number;
				}
			}
		}
		String level1nums = "";                    
		// 循环上一期，先找出上一期错了的
		for(int j = 0; j < tds1.size(); j++){
			String txt = tds1.get(j).toString();
			if(txt.contains("terror")){
				// 并且正确率在88%以上才取用
				Integer zql = Integer.parseInt(tds2.get(j).getElementsByTag("strong").get(0).html().replace("%", ""));
				if(zql > 88){
					Elements tdr = tds.get(j+1).getElementsByTag("b");
					String a = tdr.get(0).html();
					if(!level1nums.contains(a)){
						level1nums = level1nums+a;
					}
				}
			}
		}
		// 获取当前期的所有数据，并得出没有被杀的号
		String b = "";
		for(int k = 1; k < tds.size()-1; k++){
			Element txt1 = tds.get(k);
			Elements ans = txt1.getElementsByTag("b");
			b = b+ans.get(0).html();
		}
		String nums = Utils.filterData(b);
		wangyidata = level0nums+","+level1nums+","+level2nums+","+nums;
		return wangyidata;
	}

	private void saveToDatabase(String qihao,String lastQihao,String dataWangyi,String data360,int position){
		String[] wys = dataWangyi.split(",");
		String[] tszs = data360.split(",");
		String fivenums = "";
		String l1 = "";
		if(!"".equals(wys[0]+tszs[0])){
			l1 = Utils.replaceRepeat(wys[0]+tszs[0]);
		}
		String l2 = "";
		if(!"".equals(wys[1]+tszs[1])){
			l2 = Utils.replaceRepeat(wys[1]+tszs[1]);
		}
		String l3 = "";
		if(!"".equals(wys[2]+tszs[2])){
			l3 = Utils.replaceRepeat(wys[2]+tszs[2]);
		}
		if(l1.length() > 5){
			fivenums = Utils.formatIntArrayToString(Utils.getRandomFromArray(Utils.formatStringToIntArray(l1), 5));
		}else{
			fivenums = fivenums+l1;
			int nc1 = 5-(l1.length());
			// 先要过滤l2中存在的l1数据
			l2 = Utils.filterData(l1, l2);
			if((l1+l2).length() > 5 && !"".equals(l2)){
				fivenums = fivenums + Utils.formatIntArrayToString(Utils.getRandomFromArray(Utils.formatStringToIntArray(l2), nc1));
			}else{
				//过滤掉l3中存在的l1+l2的数据
				l3 = Utils.filterData(l1+l2, l3);
				fivenums = fivenums+l2+l3;
				if(fivenums.length() < 5){
					fivenums = fivenums + Utils.getRandomNumber(5-fivenums.length());
				}else if(fivenums.length() > 5){
					int nc2 = (5-(l2+l1).length());
					fivenums = (fivenums + Utils.formatIntArrayToString(Utils.getRandomFromArray(Utils.formatStringToIntArray(l3), nc2))).substring(0, 5);
				}
			}
		}

		//System.out.println("final :   "+fivenums);
		String oqihao = DBHelper.getSSCPlanQihao(position);
		if(!oqihao.equals(qihao)){
			SSCPlanBean bean = new SSCPlanBean();
			bean.setQihao(qihao);
			String levelone = wys[0]+tszs[0];
			String leveltwo = wys[1]+tszs[1];
			String levelthree = wys[2]+tszs[2];
			bean.setLevelone(levelone);
			bean.setLeveltwo(leveltwo);
			bean.setLevelthree(levelthree);
			bean.setLevelfour(Utils.filterData(wys[3]+tszs[3]));
			bean.setFivenum(fivenums);
			bean.setThreenum(fivenums.substring(0, 3));
			bean.setFournum(fivenums.substring(0, 4));
			bean.setTwonum(fivenums.substring(3,5));
			bean.setLevelott(Utils.replaceRepeat(levelone+leveltwo+levelthree));
			bean.setPostion(position);
			DBHelper.insertSSCPlan(bean);
		}
		
		// 更改上一期是否正确数据
		SSCBean bean = DBHelper.getRecordByQihao(lastQihao);
		if(bean == null){return;}
		SSCFiveUpdateBean uBean = new SSCFiveUpdateBean();
		uBean.setQihao(bean.getQihao());
		SSCLastResultBean rBean = DBHelper.getPlanRecordByQihao(uBean.getQihao(),position);
		if(rBean == null){return;}
		int num = -1;
		switch(position){
			case 1:
				num = bean.getTenthousand();
			break;
			case 2:
				num = bean.getThousand();
			break;
			case 3:
				num = bean.getHundred();
			break;
			case 4:
				num = bean.getTen();
			break;
			case 5:
				num = bean.getOne();
			break;
			default:
				num = -1;
			break;
		}
		uBean.setResultnum(num+"");
		if(rBean.getFivenum().contains(num+"")){
			uBean.setFivewr("1");
		}else{
			uBean.setFivewr("0");
		}
		if(rBean.getFournum().contains(num+"")){
			uBean.setFourwr("1");
		}else{
			uBean.setFourwr("0");
		}
		if(rBean.getThreenum().contains(num+"")){
			uBean.setThreewr("1");
		}else{
			uBean.setThreewr("0");
		}
		if(rBean.getTwonum().contains(num+"")){
			uBean.setTwowr("1");
		}else{
			uBean.setTwowr("0");
		}
		if(rBean.getLevelottnum().contains(num+"")){
			uBean.setLevelottwr("1");
		}else{
			uBean.setLevelottwr("0");
		}
		DBHelper.updateLastSSCRecord(uBean,position);
	}

}
